package app.pages;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.springframework.beans.factory.annotation.Configurable;
import org.vaadin.navigator7.Page;

import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Upload;
import com.vaadin.ui.Upload.FailedEvent;
import com.vaadin.ui.Upload.FailedListener;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Upload.SucceededListener;

/** 
 * 
 * @author Faton Alia
 * @author David Gianorio
 * @author Nachman Mathieu
 * 
 * This class contains will be used to upload Application in the server */

@Page
@Configurable(preConstruction = true)
public class MyUploaderPage extends CustomComponent implements SucceededListener, FailedListener, Receiver {
	
	Panel root; // Root element for contained components.
	File  file; // File to write to.
	
	// Constructor
	public MyUploaderPage() {

		root = new Panel();
		setCompositionRoot(root);
		
		// Create the Upload component.
		final Upload upload = new Upload("Upload the file here", this);
		
		// Use a custom button caption instead of plain "Upload".
		upload.setButtonCaption("Upload Now");
		
		// Listen for events regarding the success of upload.
		upload.addListener((SucceededListener) this);
		upload.addListener((FailedListener) this);
		root.addComponent(upload);

	}
	
	// Callback method to begin receiving the upload.
	public OutputStream receiveUpload(String filename, String MIMEType) {
		
		FileOutputStream fos = null; // Output stream to write to
		file = new File("C:/eclipse" + filename);
		
		try {
			
			// Open the file for writing.
			fos = new FileOutputStream(file);
		} catch (final java.io.FileNotFoundException e) {
			
			// Error while opening the file. Not reported here.
			e.printStackTrace();
			return null;
		}
		return fos; // Return the output stream to write to
	}
	
	// This is called if the upload is finished.
	public void uploadSucceeded(SucceededEvent event) {
		// Log the upload on screen.
		root.addComponent(new Label("File " + event.getFilename() + " of type '" + event.getMIMEType() + "' uploaded."));
	}
	
	// This is called if the upload fails.
	public void uploadFailed(FailedEvent event) {
		// Log the failure on screen.
		root.addComponent(new Label("Uploading " + event.getFilename() + " of type '" + event.getMIMEType() + "' failed."));
	}
}
